package com.jia.lidao.others.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.jia.lidao.R;
import com.jia.lidao.UserUtils;
import com.jia.lidao.enity.RefreshStatusMessage;
import com.jia.lidao.others.API;
import com.jia.lidao.others.BaseFragment;
import com.jia.lidao.others.UserInfoUtil;
import com.jia.lidao.others.enity.ModelBeen;
import com.jia.lidao.others.enity.ObjectCallBack;
import com.jia.lidao.others.enity.OrderInfor;
import com.jia.lidao.others.enity.Picture;
import com.jia.lidao.others.enity.UpResponse;
import com.jia.lidao.others.ui.SelectPicAdapter;
import com.jia.lidao.others.ui.view.AppraiseHeaderView;
import com.jia.lidao.utils.ListUtil;
import com.jia.lidao.utils.LogUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;
import static com.jia.lidao.RunningContext.IMAGE_REQUEST_CODE;
import static com.jia.lidao.RunningContext.compressBySizeHeight;
import static com.jia.lidao.RunningContext.compressBySizeWidth;

/**
 * Created by 00029935 on 2017/12/8.
 */

public class AppraiseFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.construction_ca_list_ay)
    RecyclerView recyclerview;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.tv_sure)
    TextView tvSure;

    private SelectPicAdapter adapter;
    private List<Picture> pictures;
    private int readySelectPicCount = 0;
    private Boolean hasAddItem = false;
    private AppraiseHeaderView headerView;
    public static final int MAX_IMAGES_COUNT = 9;
    private StringBuilder pics = new StringBuilder();
    private int anonymous = 1;
    private OrderInfor.OrderBean orderBean;
    private int id;

    private int pos;

    private List<OrderInfor.OrderBean.OrderGoodsBean> orderGoodsBeans;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getActivity().getIntent().getIntExtra("ID", 0);
    }

    @Override
    protected int getInflateLayout() {
        return R.layout.appraise_fragment;
    }

    @Override
    protected void setUpView(View view) {
        tvTitle.setText("发布评论");
        ibBack.setImageResource(R.mipmap.share_back);
        pictures = new ArrayList<>();
        pictures.add(new Picture());
        adapter = new SelectPicAdapter(getContext());
        adapter.setData(pictures);
        headerView = new AppraiseHeaderView(getContext());

        View footview = View.inflate(getContext(), R.layout.appraise_footer_view, null);
        adapter.setHeadView(headerView);
        adapter.setFooterView(footview);

        CheckBox checkBox = (CheckBox) footview.findViewById(R.id.check);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    anonymous = 1;
                } else {
                    anonymous = 0;
                }
            }
        });
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0 || gridLayoutManager.getItemCount() - 1 == position) {
                    return gridLayoutManager.getSpanCount();    // 头部和尾部 特殊处理
                } else {
                    return 1;
                }

            }
        });

        recyclerview.setLayoutManager(gridLayoutManager);
        recyclerview.setAdapter(adapter);
        adapter.setSelectPicListener(new SelectPicAdapter.SelectPicListener() {
            @Override
            public void listener(Picture itemData, int position) {
                int count = MAX_IMAGES_COUNT - adapter.getListData().size() + 1;
                if (count < 0) {
                    count = 0;
                }
                if (count > 0) {
                    callImageSelector(1);
                    //  callImageSelector(count);
                }


            }
        });

        adapter.setRemoveItemListener(new SelectPicAdapter.RemoveItemListener() {
            @Override
            public void listener(Picture itemData, int position) {

                --readySelectPicCount;
                Log.e("HQQ", "  setRemoveItemListener : " + readySelectPicCount);
                if (readySelectPicCount < MAX_IMAGES_COUNT && !hasAddItem) {
                    List<Picture> pictures = adapter.getListData();
                    pictures.add(new Picture());
                    adapter.notifyItemInserted(position);
                    hasAddItem = true;
                }

            }
        });
        queryData(id);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick(R.id.ib_back)
    public void onClick() {
        getActivity().finish();
    }

    private void callImageSelector(int selectCount) {
        Intent intent = new Intent(getContext(), MultiImageSelectorActivity.class);
        // whether show camera
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // max select image amount
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, selectCount);
        // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        ArrayList<String> selectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
        if (selectPath != null && selectPath.size() > 0) {
            int size = selectPath.size();
            readySelectPicCount += size;


            List<Picture> listData = adapter.getListData();
            listData.get(listData.size() - 1).setUrl(selectPath.get(0));
            uploadPicOne(selectPath.get(0), listData.get(listData.size() - 1));

            for (int i = 1; i < size; i++) {
                Picture picture = new Picture();
                picture.setUrl(selectPath.get(i));
                uploadPicOne(selectPath.get(i), picture);
                listData.add(picture);
            }

            if (readySelectPicCount < MAX_IMAGES_COUNT) {
                listData.add(new Picture());
                hasAddItem = true;
            } else {
                hasAddItem = false;
            }
            // uploadPic(selectPath);

            adapter.reflashData(listData);

        }

    }

    private String compressUploadPicture(String imagePath) {

        String compressPath = Environment.getExternalStorageDirectory()
                + File.separator + SystemClock.currentThreadTimeMillis() + ".jpg";
        File file = new File(imagePath);
        if (file.exists()) {
            Bitmap bitmap = compressBySize(imagePath, compressBySizeWidth,
                    compressBySizeHeight);
            // 保存图片
            try {
                saveFile(bitmap, compressPath);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return compressPath;
        } else {
            return null;
        }
    }

    // 压缩图片尺寸
    public Bitmap compressBySize(String pathName, int targetWidth,
                                 int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        // 设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(pathName, opts);

        bitmap = rotateBitmapByDegree(bitmap, getImageDegree(pathName));
        return bitmap;
    }

    // 存储进SD卡
    public void saveFile(Bitmap bm, String fileName) throws Exception {
        File dirFile = new File(fileName);
        // 检测图片是否存在
        if (dirFile.exists()) {
            dirFile.delete(); // 删除原图片
        }
        File myCaptureFile = new File(fileName);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        // 100表示不进行压缩，70表示压缩率为30%
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    private int getImageDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    private void uploadPic(List<String> picurls) {
        progress.setVisibility(View.VISIBLE);
        String url = API.UPLOAD + UserUtils.getInstance().getAuthor().access_token;
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<UpResponse> typeToken = new TypeToken<UpResponse>() {
        };
        final int size = picurls.size();
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        for (int i = 0; i < size; i++) {
            String ul = compressUploadPicture(picurls.get(i));
            File file = new File(ul);
            postFormBuilder.addFile(String.valueOf(i), file.getName(), file);
        }

        postFormBuilder.url(url)
                .headers(heades)//
                .build()//
                .execute(new ObjectCallBack<UpResponse>(typeToken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progress.setVisibility(View.GONE);
                        showToast("上传失败");
                    }

                    @Override
                    public void onResponse(UpResponse response, int id) {
                        if (response.getErr_code() == 0) {
                            if (readySelectPicCount == MAX_IMAGES_COUNT) {
                                pics.delete(0, pics.length());
                            }

                            String url0 = response.getResult().getValue0();
                            if (!TextUtils.isEmpty(url0)) {
                                pics.append(url0);

                            }

                            String url1 = response.getResult().getValue1();
                            if (!TextUtils.isEmpty(url1)) {
                                pics.append(";");
                                pics.append(url1);
                            }

                            String url2 = response.getResult().getValue2();
                            if (!TextUtils.isEmpty(url2)) {
                                pics.append(";");
                                pics.append(url2);

                            }

                            String url3 = response.getResult().getValue3();
                            if (!TextUtils.isEmpty(url3)) {
                                pics.append(";");
                                pics.append(url3);

                            }

                            String url4 = response.getResult().getValue4();
                            if (!TextUtils.isEmpty(url4)) {
                                pics.append(";");
                                pics.append(url4);
                            }

                            String url5 = response.getResult().getValue5();
                            if (!TextUtils.isEmpty(url5)) {
                                pics.append(";");
                                pics.append(url5);
                            }

                            String url6 = response.getResult().getValue5();
                            if (!TextUtils.isEmpty(url6)) {
                                pics.append(";");
                                pics.append(url6);
                            }

                            String url7 = response.getResult().getValue7();
                            if (!TextUtils.isEmpty(url7)) {
                                pics.append(";");
                                pics.append(url7);
                            }

                            String url8 = response.getResult().getValue8();
                            if (!TextUtils.isEmpty(url8)) {
                                pics.append(url8);
                                pics.append(";");
                            }

                            String url9 = response.getResult().getValue9();
                            if (!TextUtils.isEmpty(url9)) {
                                pics.append(";");
                                pics.append(url9);
                            }

                            Log.e("HQQ", " pics : " + pics.toString());
                        }
                        showToast("上传成功！");
                        progress.setVisibility(View.GONE);
                    }
                });
    }


    private void uploadPicOne(String picurl, final Picture picture) {
        progress.setVisibility(View.VISIBLE);
        String url = API.UPLOAD + UserUtils.getInstance().getAuthor().access_token;
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<UpResponse> typeToken = new TypeToken<UpResponse>() {
        };
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        String ul = compressUploadPicture(picurl);
        File file = new File(ul);
        postFormBuilder.addFile(String.valueOf(1), file.getName(), file);

        postFormBuilder.url(url)
                .headers(heades)//
                .build()//
                .execute(new ObjectCallBack<UpResponse>(typeToken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progress.setVisibility(View.GONE);
                        showToast("上传失败");
                    }

                    @Override
                    public void onResponse(UpResponse response, int id) {
                        if (response.getErr_code() == 0) {
                            if (readySelectPicCount == MAX_IMAGES_COUNT) {
                                pics.delete(0, pics.length());
                            }

                            String url0 = response.getResult().getValue0();
                            picture.readPicUrl = url0;
                            if (!TextUtils.isEmpty(url0)) {
                                pics.append(url0);
                            }
                            picture.readPicUrl = response.getResult().getValue1();


                            Log.e("HQQ", " readPicUrl : " + picture.readPicUrl);
                        }
                        showToast("上传成功！");
                        progress.setVisibility(View.GONE);
                    }
                });
    }

    private void appraiseData(int order_goods_id, String content, int stars, String pics, int anonymous) {
        progress.setVisibility(View.VISIBLE);

        String url = API.ORDERS_GOODS_COMMENT + "order_goods_id=" + order_goods_id + "&content=" + content + "&stars=" + stars + "&pics=" + pics + "&anonymous=" + anonymous + "&access_token=" + UserUtils.getInstance().getAuthor().access_token;
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        LogUtil.printJ("comment url=" + url);

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };

        OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != progress) {
                    progress.setVisibility(View.GONE);
                }


            }

            @Override
            public void onResponse(ModelBeen response, int id) {


                if (null != response) {
                    if (response.err_code == 0) {
                        showToast("评论成功！");
                        orderGoodsBeans.get(pos).commented = 1;
                        checkandrefreshView();
                    } else {
                        showToast(response.err_msg);
                    }
                }

                if (null != progress) {
                    progress.setVisibility(View.GONE);
                }


            }
        });
    }

    @OnClick(R.id.tv_sure)
    public void onClickSure() {
        String content = headerView.getContentAppraise();
        if (TextUtils.isEmpty(content)) {
            showToast("请输入评论！");
            return;
        }


        StringBuffer stringBuffer = new StringBuffer();
        List<Picture> pictur = adapter.getListData();
        if (null != pictur && !pictur.isEmpty()) {
            int size = pictur.size();
            LogUtil.printJ("size=" + size);
            for (int i = 0; i < size; i++) {
                Picture p = pictur.get(i);
                if (!TextUtils.isEmpty(p.readPicUrl)) {
                    stringBuffer.append(p.readPicUrl);
                }

                if (i != size - 1) {
                    stringBuffer.append(";");
                }
            }

        }
        if (TextUtils.isEmpty(stringBuffer.toString())) {
            showToast("请上传图片！");
            return;
        }

        Log.e("HQQ", "stringBuffer : " + stringBuffer.toString());
        appraiseData(orderGoodsBeans.get(pos).getOrder_goods_id(), headerView.getContentAppraise(), headerView.getStarsCount(), stringBuffer.toString(), anonymous);
    }


    private void queryData(int id) {

        String url = API.ORDERS_DETIAL + id + "?" + "&access_token=" + UserUtils.getInstance().getAuthor().access_token;
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        LogUtil.printJ("url=" + url);

        TypeToken<OrderInfor> typeToken = new TypeToken<OrderInfor>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<OrderInfor>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(OrderInfor response, int id) {

                if (null != response) {
                    OrderInfor.OrderBean orderBean = response.getOrder();
                    orderGoodsBeans = orderBean.getOrder_goods();
                    AppraiseFragment.this.orderBean = orderBean;
                    checkandrefreshView();
                }
            }
        });

    }


    private void checkandrefreshView() {
        if (ListUtil.isEmpty(orderGoodsBeans)) {
            showToast("商品异常");
            return;
        }
        for (pos = 0; pos < orderGoodsBeans.size(); pos++) {
            if (orderGoodsBeans.get(pos).commented == 0) {
                break;
            }
        }
        LogUtil.printJ("pos=" + pos);
        if (pos >= orderGoodsBeans.size()) {
            showToast("评价完成");
            EventBus.getDefault().post(new RefreshStatusMessage());
            getActivity().finish();
            return;
        } else {
            pictures = new ArrayList<>();
            pictures.add(new Picture());
            adapter.reflashData(pictures);
            headerView.setData(orderGoodsBeans.get(pos));
        }
    }

}
